'''
Created on Feb 1, 2010

@author: madsk
'''

from PyQt4 import QtCore, QtGui

class TableModel(QtCore.QAbstractTableModel):
    COLUMNS = 3
    
    def __init__(self, parent = None):
        super(TableModel, self).__init__(parent)
        self._header = ('Task ID', 'Last operation', 'Progress (%)')
        self._tasks = []
        
    def rowCount(self, parent = QtCore.QModelIndex()):
        # If a parent is given we must return zero - we are not building a tree here.
        if parent.isValid():
            return 0

        return len(self._tasks)
    
    def columnCount(self, parent = QtCore.QModelIndex()):
        # If a parent is given we must return zero - we are not building a tree here.
        if parent.isValid():
            return 0
        
        # Return the fixed number of columns.
        return 3
    
    def headerData(self, column, orientation, role = QtCore.Qt.DisplayRole):
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return QtCore.QVariant(self._header[column])
        return QtCore.QVariant()
    
    def data(self, index, role = QtCore.Qt.DisplayRole):
        if (not index.isValid()) or role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()
            
        return QtCore.QVariant(self._tasks[index.row()][index.column()])
    
    def taskStarted(self, taskid):
        self._tasks.append([taskid, 'None', 0])
        self.dataChanged.emit(self.createIndex(len(self._tasks) - 1, 0),
                              self.createIndex(len(self._tasks) - 1, 2))
        
    def taskProgress(self, taskid, progress, comment):
        for x in range(0, len(self._tasks)):
            if self._tasks[x][0] == taskid:
                self._tasks[x][1] = comment
                self._tasks[x][2] = int(progress * 100)
                self.dataChanged.emit(self.createIndex(x, 1),
                                      self.createIndex(x, 2))
                break
                
    def taskFinished(self, taskid):
        for x in range(0, len(self._tasks)):
            if self._tasks[x][0] == taskid:
                self._tasks.pop(x)
                self.dataChanged.emit(self.createIndex(x, 0),
                                      self.createIndex(len(self._tasks) - 1, 2))
                break
                